// douyin_downloader.js

const axios = require("axios"); // 使用 require 替换 import
const fs = require("fs");       // 使用 require 替换 import

async function getVideoUrl(shareUrl) {
    const headers = {
        "User-Agent":
            "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/121.0.2277.107 Version/17.0 Mobile/15E148 Safari/604.1",
    };

    // 第一次请求，获取 video_id
    const firstResp = await axios.get(shareUrl, { headers });

    // 获取跳转后的真实地址，相当于 Python 的 response.url
    const redirectUrl = firstResp.request.res.responseUrl;

    // 提取 video_id
    const videoId = redirectUrl.split("?")[0].replace(/\/$/, "").split("/").pop();

    console.log("videoId:"+videoId);

    const realUrl = `https://www.iesdouyin.com/share/video/${videoId}`;
    console.log("解析链接:", realUrl);

    const resp = await axios.get(realUrl, { headers });
    const html = resp.data;
    // 用正则提取 window._ROUTER_DATA
    const pattern = /window\._ROUTER_DATA\s*=\s*(.*?)<\/script>/s;
    const match = html.match(pattern);
    if (!match || !match[1]) {
        throw new Error("解析视频 JSON 信息失败");
    }

    const jsonData = JSON.parse(match[1].trim());
    // const data =
    //     jsonData["loaderData"][`video_${videoId}/page`]["videoInfoRes"][
    //         "item_list"
    //         ][0];

    const data =
        jsonData["loaderData"][`video_(id)/page`]["videoInfoRes"][
            "item_list"
            ][0];

    let videoUrl = data["video"]["play_addr"]["url_list"][0];
    videoUrl = videoUrl.replace("playwm", "play");

    return videoUrl;
}

async function downloadVideo(videoUrl, savePath = "video.mp4", onProgress = () => {}) {
    const headers = {
        "User-Agent":
            "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/121.0.2277.107 Version/17.0 Mobile/15E148 Safari/604.1",
    };

    const resp = await axios.get(videoUrl, { headers, responseType: "stream" });
    const totalLength = resp.headers['content-length'] ? parseInt(resp.headers['content-length'], 10) : 0;
    let downloadedLength = 0;

    const writer = fs.createWriteStream(savePath);
    resp.data.on('data', (chunk) => {
        downloadedLength += chunk.length;
        if (totalLength > 0) {
            const percent = ((downloadedLength / totalLength) * 100).toFixed(2);
            onProgress({ percent: parseFloat(percent), downloaded: downloadedLength, total: totalLength });
        } else {
            onProgress({ downloaded: downloadedLength });
        }
    });

    resp.data.pipe(writer);

    return new Promise((resolve, reject) => {
        writer.on("finish", () => {
            console.log(`视频已下载到 ${savePath}`);
            resolve();
        });
        writer.on("error", (err) => {
            console.error("视频下载失败:", err);
            fs.unlink(savePath, () => reject(err));
        });
    });
}

// 使用 CommonJS 导出函数
module.exports = { getVideoUrl, downloadVideo };